package pow

import (
	"Blockchain/tools"
	"bytes"
	"math/big"
	"strconv"
)
/**
*@author:张子寒
*@QQ:1594426628
*@phone:15279093203
*@DateTime: 2022/4/12 8:54
**/
const BITS = 15

type ProofOfWork struct {
	PrevHash []byte
	TimeStamp int64
	Data []byte
	Target *big.Int
}
func NewPow(data []byte,timeStamp int64,prevHash []byte)*ProofOfWork{
	//创建大整数类型
	target := big.NewInt(1)
	target = target.Lsh(target, 255-BITS)
	pow:=ProofOfWork{
		PrevHash: prevHash,
		TimeStamp: timeStamp,
		Data: data,
		Target: target,
	}
		return &pow
}
func (pow *ProofOfWork)Run()([]byte,int64){
	var nonce int64
	nonce=0
	timeByte := []byte(strconv.FormatInt(pow.TimeStamp, 10))
	//转换 把[]byte 转成 大整数类型
	num := big.NewInt(0)
	for{
		nonceByte := []byte(strconv.FormatInt(nonce, 10))
		hashByte := bytes.Join([][]byte{pow.PrevHash, pow.Data, timeByte, nonceByte}, []byte{})
		hash := tools.SetHash(hashByte)
		num= num.SetBytes(hash)
		if num.Cmp(pow.Target)==-1 {
			return hash,nonce
		}
	}
}